<?php

namespace App\Admin\Forms\Config;

use App\Helper\KeysHandler;
use App\Models\Config;
use Dcat\Admin\Widgets\Form;
use Illuminate\Support\Facades\Cache;

class ConfigForm extends Form
{
    /**
     * Handle the form request.
     *
     * @param array $input
     *
     * @return mixed
     */
    public function handle(array $input)
    {
        foreach ($input as $name => $content) {
            Config::query()->where('name', $name)->update(['content' => $content]);
        }
        Cache::forget(KeysHandler::CONFIG);
        return $this
            ->response()
            ->success('操作成功.')
            ->refresh();
    }

    /**
     * Build a form here.
     */
    public function form()
    {
        $config = Config::all();
        foreach ($config as $item) {
            if (in_array($item->name, ['logo', 'banner'])) {
                $this->image($item->name, $item->description)
                    ->move('images/' . date('Y') . '/' . date('m') . '/' . date('d'))
                    ->uniqueName()
                    ->autoUpload()
                    ->required()
                    ->default($item->content)
                    ->removable(false);
            } else {
                $this->text($item->name, $item->description)->default($item->content)->required();
            }
        }
    }

}
